# -*- coding: UTF-8 -*-
__author__ = 'czyigy'

from twisted.protocols.basic import LineOnlyReceiver

from logger import logger
import socket

class ServerProtocol(LineOnlyReceiver):
    def lineReceived(self, string):
        print string

    def getId(self):
        return str(self.transport.getPeer())

    def getIPaddr(self):
        ipAddr = "{ip}:{port}".format(ip = self.transport.getPeer().host,port = self.transport.getPeer().port)

        return ipAddr

    def connectionMade(self):
        logger.info("New Connection:%s"% self.getId())
        self.transport.getHandle().setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        self.transport.getHandle().setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60)
        self.transport.getHandle().setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5)
        self.transport.getHandle().setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3)
        self.factory.addClient(self)

    def connectionLost(self, reason):
        logger.info( "Lost Connection:%s"% self.getId())
        self.factory.delClient(self)

    def dataReceived(self, buffer):
        ##reveive data
        if buffer.find("cmd_type") != -1:
            logger.info( buffer)
            # self.transport.write(json.dumps({"result":True,"msg":"receive ok"}) +'\n')
        self.factory.decodeData(self,buffer)

